<template>
  <view>
    <cu-custom class="navBox" bgColor="bg-blue" :isBack="true">
      <block slot="content">地图轨迹</block>
    </cu-custom>

    <view class="container">
      <map
        id="map"
        :latitude="latitude"
        :longitude="longitude"
        :markers="covers"
        :style="{ width: '100%', height: mapHeight + 'px' }"
        :scale="8"
        :polyline="polyline"
        :show-location="true"
        :enable-rotate="true"
        :enable-overlooking="true"
        :enable-3D="true"
      >
      </map>

      <view class="selectBox">
        <view class="select-item">
          <text>起点：</text>
          <view class="picker" @tap="chooseLocation('start')">
            {{ startCity || "点击选择起点位置" }}
          </view>
        </view>

        <!-- 途径城市 -->
        <view
          v-for="(waypoint, index) in waypoints"
          :key="index"
          class="select-item"
        >
          <view class="waypoint-header">
            <text>途径{{ index + 1 }}：</text>
            <text
              class="delete-btn"
              @tap="deleteWaypoint(index)"
              v-if="waypoint.city"
              >×</text
            >
          </view>
          <view class="picker" @tap="chooseLocation('waypoint', index)">
            {{ waypoint.city || "点击选择途径位置" }}
          </view>
        </view>

        <view class="select-item">
          <text>终点：</text>
          <view class="picker" @tap="chooseLocation('end')">
            {{ endCity || "点击选择终点位置" }}
          </view>
        </view>
      </view>

      <view class="btnBox">
        <button
          :disabled="!startLocation || !endLocation"
          @click="planRoute"
          class="cu-btn bg-blue round shadow lg"
          style="margin-bottom: 20rpx"
        >
          规划路线
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import AmapWX from "@/common/amap-wx.js";

export default {
  data() {
    return {
      map: null,
      windowHeight: 0,
      mapHeight: 0,
      timer: null,

      isDisabled: true,
      playIndex: 1,

      // 默认路线数据
      defaultRoute: {
        start: {
          city: "福州站",
          location: {
            lat: 26.113859,
            lng: 119.320117,
          },
        },
        waypoints: [
          {
            city: "杭州站",
            location: {
              lat: 30.243749,
              lng: 120.182488,
            },
          },
          {
            city: "上海站",
            location: {
              lat: 31.249601,
              lng: 121.455704,
            },
          },
          {
            city: "北京站",
            location: {
              lat: 39.902802,
              lng: 116.427048,
            },
          },
        ],
        end: {
          city: "沈阳站",
          location: {
            lat: 41.794601,
            lng: 123.393368,
          },
        },
      },

      startCity: "", // 选择的起点城市
      endCity: "", // 选择的终点城市
      startLocation: null, // 起点坐标
      endLocation: null, // 终点坐标

      id: 0,
      title: "map",
      latitude: 35.0, // 修改默认中心点为全国中心位置
      longitude: 120.0,

      // 标记点
      covers: [],
      // 线
      polyline: [],
      // 当前使用的坐标数据
      coordinate: [],

      amapSdk: null, // 高德地图SDK实例
      waypoints: Array(3)
        .fill()
        .map(() => ({
          city: "",
          location: null,
        })),
      // 移动标记点
      movingMarker: null,
      animationTimer: null,

      // 小车角度
      carAngle: 0,
    };
  },
  onLoad() {
    // 初始化高德地图SDK
    this.amapSdk = new AmapWX({
      key: "97c6c35b28a744442090f63bec8c83aa", // 请替换为您的高德地图key
    });

    // 获取系统信息设置地图高度
    uni.getSystemInfo({
      success: (res) => {
        this.windowHeight = res.windowHeight;
        // 设置地图高度为屏幕高度的70%
        this.mapHeight = res.windowHeight * 0.7;
      },
    });

    // 加载默认路线数据
    this.loadDefaultRoute();
  },
  methods: {
    // 加载默认路线数据
    loadDefaultRoute() {
      // 设置起点
      this.startCity = this.defaultRoute.start.city;
      this.startLocation = this.defaultRoute.start.location;

      // 设置途径点
      this.defaultRoute.waypoints.forEach((wp, index) => {
        this.waypoints[index] = {
          city: wp.city,
          location: wp.location,
        };
      });

      // 设置终点
      this.endCity = this.defaultRoute.end.city;
      this.endLocation = this.defaultRoute.end.location;

      // 更新地图显示
      this.updateMapView();

      // 自动规划路线
      this.$nextTick(() => {
        this.planRoute();
      });
    },
    // 选择位置
    chooseLocation(type, index) {
      uni.chooseLocation({
        success: (res) => {
          if (type === "start") {
            this.startCity = res.name;
            this.startLocation = {
              lat: res.latitude,
              lng: res.longitude,
            };
          } else if (type === "waypoint") {
            this.waypoints[index] = {
              city: res.name,
              location: {
                lat: res.latitude,
                lng: res.longitude,
              },
            };
          } else {
            this.endCity = res.name;
            this.endLocation = {
              lat: res.latitude,
              lng: res.longitude,
            };
          }

          // 更新地图显示
          this.updateMapView();
        },
      });
    },

    // 删除途径点
    deleteWaypoint(index) {
      this.waypoints[index] = {
        city: "",
        location: null,
      };
      this.updateMapView();
    },

    // 规划路线
    async planRoute() {
      if (!this.startLocation || !this.endLocation) return;

      uni.showLoading({
        title: "规划路线中...",
      });

      try {
        // 收集所有有效的途径点
        const validWaypoints = this.waypoints.filter(
          (wp) => wp.location !== null
        );

        // 如果没有途径点，直接规划起点到终点的路线
        if (validWaypoints.length === 0) {
          await new Promise((resolve, reject) => {
            this.amapSdk.getDrivingRoute({
              origin: `${this.startLocation.lng},${this.startLocation.lat}`,
              destination: `${this.endLocation.lng},${this.endLocation.lat}`,
              success: (result) => {
                this.coordinate = result.points;
                resolve();
              },
              fail: reject,
            });
          });
        } else {
          // 构建完整路线：起点 -> 途径点1 -> 途径点2 -> ... -> 终点
          const allPoints = [
            this.startLocation,
            ...validWaypoints.map((wp) => wp.location),
            this.endLocation,
          ];
          const routeSegments = [];

          // 规划每一段路线
          for (let i = 0; i < allPoints.length - 1; i++) {
            const from = allPoints[i];
            const to = allPoints[i + 1];
            const segment = await new Promise((resolve, reject) => {
              this.amapSdk.getDrivingRoute({
                origin: `${from.lng},${from.lat}`,
                destination: `${to.lng},${to.lat}`,
                success: (result) => {
                  resolve(result.points);
                },
                fail: reject,
              });
            });
            routeSegments.push(segment);
          }

          // 合并所有路段
          this.coordinate = this.mergeRouteSegments(routeSegments);
        }

        // 显示完整路线
        this.polyline = [
          {
            points: this.coordinate,
            color: "#1aad19",
            width: 4,
            arrowLine: true,
          },
        ];

        // 启用轨迹回放按钮
        this.isDisabled = false;

        uni.hideLoading();
        uni.showToast({
          title: "路线规划成功",
          icon: "success",
        });
      } catch (error) {
        console.error("路线规划失败:", error);
        uni.hideLoading();
        uni.showToast({
          title: "路线规划失败",
          icon: "none",
        });
      }
    },

    // 合并路线段
    mergeRouteSegments(segments) {
      return segments.reduce((acc, curr) => acc.concat(curr), []);
    },

    // 更新地图视野
    updateMapView() {
      const points = [];
      if (this.startLocation) {
        points.push({
          latitude: this.startLocation.lat,
          longitude: this.startLocation.lng,
          iconPath: "/static/start.png",
          width: 32,
          height: 32,
        });
      }

      this.waypoints.forEach((wp) => {
        if (wp.location) {
          points.push({
            latitude: wp.location.lat,
            longitude: wp.location.lng,
            iconPath: "/static/location.png",
            width: 32,
            height: 32,
          });
        }
      });

      if (this.endLocation) {
        points.push({
          latitude: this.endLocation.lat,
          longitude: this.endLocation.lng,
          iconPath: "/static/end.png",
          width: 32,
          height: 32,
        });
      }

      this.covers = points;
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  position: relative;
}

.selectBox {
  width: 90%;
  margin: 20rpx auto;
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.select-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;

  &:last-child {
    margin-bottom: 0;
  }

  text {
    width: 100rpx;
    font-size: 28rpx;
    color: #333;
  }

  .waypoint-header {
    display: flex;
    align-items: center;
    padding-right: 5rpx;

    .delete-btn {
      width: auto;
      margin-left: 10rpx;
      color: #e64340;
      font-size: 32rpx;
      padding: 0 10rpx;
    }
  }

  .picker {
    flex: 1;
    padding: 15rpx 20rpx;
    background-color: #f8f8f8;
    border-radius: 8rpx;
    font-size: 28rpx;
    color: #666;
  }
}

.btnBox {
  width: 90%;
  margin: 30rpx auto;

  .cu-btn {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
  }
}
</style>
